import { useModel } from "@umijs/max"
import { App, Button, Card, Modal, Slider } from "antd"
import React, { useState } from "react"
import { Image, Layer, Rect, Stage } from "react-konva"

// 图像组件
const TotalBoardImage: React.FC<{ imageData: string | null }> = ({ imageData }) => {
  const [image, setImage] = useState<HTMLImageElement | null>(null)

  React.useEffect(() => {
    if (imageData) {
      const img = new window.Image()
      img.src = `data:image/jpeg;base64,${imageData}`
      img.onload = () => {
        setImage(img)
      }
    } else {
      setImage(null)
    }
  }, [imageData])

  return (
    <Image
      image={image}
      width={image ? image.width : 900}
      height={image ? image.height : 880}
    />
  )
}

// 手动标注点组件
interface HandLabelProps {
  x: number
  y: number
  name: string
  callBack: (x: number, y: number) => void
}

const HandLabel: React.FC<HandLabelProps> = ({ x, y, name, callBack }) => {
  const handleDragMove = (e: any) => {
    callBack(e.target.x(), e.target.y())
  }

  return (
    <Rect
      x={x}
      y={y}
      width={10}
      height={10}
      fill="red"
      draggable
      onDragMove={handleDragMove}
    />
  )
}

const BoardSizeHandLabelModal: React.FC = () => {
  const { callPy } = useModel("websocketModel")
  const {
    handLabelModalVisible,
    handLabelImageData,
    handLabelSize,
    labelBoardSizeMm,
    updateProduceData
  } = useModel("produceModel")
  const { message } = App.useApp()

  // 状态
  const [widthAdjustValue, setWidthAdjustValue] = useState(0)
  const [heightAdjustValue, setHeightAdjustValue] = useState(0)
  const [p7, setP7] = useState({ x: 30, y: 30 })
  const [p8, setP8] = useState({ x: 300, y: 300 })
  const [innerBoardAngle, setInnerBoardAngle] = useState(0)

  const closeModal = () => {
    updateProduceData({
      handLabelModalVisible: false,
      handLabelImageData: null,
      handLabelSize: [],
      labelBoardSizeMm: []
    })
  }

  const handleWidthChange = (value: number) => {
    setWidthAdjustValue(value)
  }

  const handleHeightChange = (value: number) => {
    setHeightAdjustValue(value)
  }

  const handleAfterSizeChange = async () => {
    const args = [widthAdjustValue, heightAdjustValue]
    const response = await callPy("produce", "inner_board_size_change_from_web", args)
    if (!response.state) {
      message.error("尺寸调整失败:" + response.info, 5)
    }
  }

  const handleInnerBoardSizeOk = async () => {
    closeModal()
    const args = [[p7.x, p7.y], -innerBoardAngle]
    const response = await callPy("produce", "hand_inner_board_size_ok_from_web", args)
    setWidthAdjustValue(0)
    setHeightAdjustValue(0)
    if (response.state) {
      message.success("标注内板尺寸成功")
      closeModal()
    } else {
      message.error("标注内板尺寸失败:" + response.info, 5)
    }
  }

  return (
    <Modal
      title={
        <span style={{ color: "orange", fontSize: 16, fontWeight: "bold" }}>
          内板尺寸人工标注框
        </span>
      }
      open={handLabelModalVisible}
      width="90vw"
      style={{ top: 5 }}
      footer={null}
      closable={false}
    >
      <Card>
        <Card.Grid style={{ width: "70%", textAlign: "left" }}>
          <Stage width={900} height={600}>
            <Layer>
              <TotalBoardImage imageData={handLabelImageData} />
              <Rect
                width={handLabelSize[0]}
                height={handLabelSize[1]}
                strokeWidth={2}
                stroke="#dfe333"
                x={p7.x}
                y={p7.y}
                rotation={innerBoardAngle}
              />
              <HandLabel
                x={30}
                y={30}
                name="左上角"
                callBack={(x, y) => setP7({ ...p7, x, y })}
              />
              <HandLabel
                x={300}
                y={300}
                name="内框旋转"
                callBack={(x, y) => setInnerBoardAngle((y - p8.y) / 20)}
              />
            </Layer>
          </Stage>
        </Card.Grid>
        <Card.Grid style={{ width: "30%", textAlign: "left" }}>
          <div style={{ marginLeft: 16, marginRight: 16 }}>
            宽度调整
            <Slider
              value={widthAdjustValue}
              max={20}
              min={-20}
              onChange={handleWidthChange}
              onChangeComplete={handleAfterSizeChange}
            />
          </div>
          <div style={{ marginLeft: 16, marginRight: 16 }}>
            高度调整
            <Slider
              value={heightAdjustValue}
              max={20}
              min={-20}
              onChange={handleHeightChange}
              onChangeComplete={handleAfterSizeChange}
            />
          </div>
          <div style={{ marginLeft: 16, marginTop: 30 }}>
            <span style={{ color: "#0000FF", fontSize: 16 }}>标注尺寸:&nbsp;&nbsp;</span>
            <span>
              (宽,高) = ({labelBoardSizeMm[0]},&nbsp;{labelBoardSizeMm[1]})
            </span>
          </div>
          <div style={{ marginLeft: 16, marginTop: 20 }}>
            <Button type="primary" onClick={handleInnerBoardSizeOk}>
              标注内板尺寸OK
            </Button>
          </div>
        </Card.Grid>
      </Card>
    </Modal>
  )
}

export default () => (
  <App>
    <BoardSizeHandLabelModal />
  </App>
)
